#!/usr/bin/env python3
"""
验证DataPlexus数据治理平台时区修复的完整性
检查所有Python文件中是否还有使用datetime.utcnow的地方
"""

import os
import re
from pathlib import Path

def find_datetime_utcnow_usage():
    """查找所有使用datetime.utcnow的地方"""
    backend_dir = Path(__file__).parent.parent / 'backend'
    python_files = list(backend_dir.rglob('*.py'))
    
    issues = []
    
    for file_path in python_files:
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
                lines = content.split('\n')
                
                for line_num, line in enumerate(lines, 1):
                    if 'datetime.utcnow' in line:
                        # 排除注释行
                        if line.strip().startswith('#'):
                            continue
                        
                        issues.append({
                            'file': str(file_path.relative_to(backend_dir)),
                            'line': line_num,
                            'content': line.strip()
                        })
        except Exception as e:
            print(f"读取文件失败: {file_path} - {e}")
    
    return issues

def check_timezone_imports():
    """检查是否正确导入了时区工具"""
    backend_dir = Path(__file__).parent.parent / 'backend'
    python_files = list(backend_dir.rglob('*.py'))
    
    files_with_datetime = []
    files_with_timezone_import = []
    
    for file_path in python_files:
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
                
                # 检查是否使用了datetime相关功能
                if any(pattern in content for pattern in [
                    'datetime.now', 'datetime.utcnow', 'get_shanghai_now',
                    'Column(DateTime', 'default=datetime', 'default=get_shanghai'
                ]):
                    files_with_datetime.append(str(file_path.relative_to(backend_dir)))
                
                # 检查是否导入了时区工具
                if 'from app.utils.timezone_utils import' in content:
                    files_with_timezone_import.append(str(file_path.relative_to(backend_dir)))
                    
        except Exception as e:
            print(f"读取文件失败: {file_path} - {e}")
    
    return files_with_datetime, files_with_timezone_import

def main():
    print("🔍 DataPlexus 时区修复验证工具")
    print("=" * 50)
    
    # 检查是否还有datetime.utcnow的使用
    print("1. 检查剩余的 datetime.utcnow 使用...")
    issues = find_datetime_utcnow_usage()
    
    if issues:
        print(f"❌ 发现 {len(issues)} 处仍在使用 datetime.utcnow:")
        for issue in issues:
            print(f"   📁 {issue['file']}:{issue['line']}")
            print(f"      {issue['content']}")
            print()
    else:
        print("✅ 未发现 datetime.utcnow 的使用")
    
    print()
    
    # 检查时区导入情况
    print("2. 检查时区工具导入情况...")
    files_with_datetime, files_with_timezone_import = check_timezone_imports()
    
    print(f"📊 统计信息:")
    print(f"   - 使用时间功能的文件: {len(files_with_datetime)} 个")
    print(f"   - 已导入时区工具的文件: {len(files_with_timezone_import)} 个")
    
    # 找出可能需要导入时区工具的文件
    missing_imports = set(files_with_datetime) - set(files_with_timezone_import)
    if missing_imports:
        print(f"⚠️  可能需要导入时区工具的文件 ({len(missing_imports)} 个):")
        for file in sorted(missing_imports):
            print(f"   📁 {file}")
    else:
        print("✅ 所有使用时间功能的文件都已正确导入时区工具")
    
    print()
    
    # 总结
    if not issues and not missing_imports:
        print("🎉 时区修复验证通过！")
        print("   ✅ 所有 datetime.utcnow 已替换为 get_shanghai_now")
        print("   ✅ 所有相关文件已正确导入时区工具")
        print("   ✅ 系统时间将统一使用上海时区")
    else:
        print("⚠️  时区修复需要进一步处理:")
        if issues:
            print(f"   - 还有 {len(issues)} 处 datetime.utcnow 需要替换")
        if missing_imports:
            print(f"   - 还有 {len(missing_imports)} 个文件可能需要导入时区工具")
    
    return len(issues) == 0 and len(missing_imports) == 0

if __name__ == "__main__":
    success = main()
    exit(0 if success else 1)
